/*
 * @Descripttion:
 * @version: v1.0
 * @Author: LiWen
 * @Date: 2022-02-23 21:02:28
 * @LastEditors: LiWen
 * @LastEditTime: 2022-03-22 17:01:11
 */
import { createWebHashHistory, createRouter } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { copyObjectDeep, setDocumentTitle, travelTree } from '../common/utils/normalUtils'
import Login from '../views/login/index.vue'
import Layout from '../views/main/index.vue'
import HomeView from '../views/main/home/index.vue'
import DealerView from '../views/main/dealer/index.vue'
import RebateView from '../views/main/rebate/index.vue'
import SettingView from '../views/main/setting/index.vue'
import { appState, initLoginInfo, initReloadSystem, showAppLoading } from '../common/manager/appManager'
import { clearToken, getToken, validToken } from '../common/manager/permission'
import routeConst from './routeConst'

// 公共路由 直接写成静态路由 只做后端权限验证 不让后端单独提供接口了

const mainViews = [
    {
        path: routeConst.HOME,
        name: routeConst.HOME,
        component: HomeView,
        meta: { title: '订单管理', icon: 'dingdan1' }
    },
    {
        path: routeConst.SETTING_DEALER,
        name: routeConst.SETTING_DEALER,
        component: DealerView,
        meta: { title: '分销商管理', icon: 'renyuanguanli2' }
    },
    {
        path: routeConst.SETTING_REBATE,
        name: routeConst.SETTING_REBATE,
        component: RebateView,
        meta: { title: '商品返点管理', icon: 'eduguanli1' }
    }
    // {
    //     path: routeConst.SETTING,
    //     name: routeConst.SETTING,
    //     component: SettingView,
    //     meta: { title: '配置合并', icon: 'setting' }
    // }
]

const constantRoutes = [
        {
            path: '/:pathMatch(.*)*',
            component: () =>
                import(/* webpackChunkName: "404" */ '../views/error/404.vue')
        },
        {
            path: routeConst.ERROR_401,
            component: () =>
                import(/* webpackChunkName: "401" */ '../views/error/401.vue')
        },
        {
            path: routeConst.ERROR_403,
            component: () =>
                import(/* webpackChunkName: "403" */ '../views/error/403.vue')
        },
        {
            path: routeConst.LOGIN,
            name: routeConst.LOGIN,
            component: Login
        },
        {
            path: routeConst.MAIN,
            name: routeConst.MAIN,
            component: Layout,
            layout: true,
            children: [...mainViews]
        }
    ]

/**
 *
 */
export function getHomeMenuList() {
  return mainViews.map((view:any) => {
      return { ...view, label: view.meta.title, icon: view.meta.icon }
  })
}


NProgress.configure({ showSpinner: false })
export const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes,
    scrollBehavior(to:any, from:any, savedPosition:any) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
})

/**
 * 统一路由跳转 内部调用入口
 */
export function changeRoute(path:string, query:any = {}, replace = false):Promise<any> {
    if (replace) return router.replace({ path, query })
    return router.push({ path, query })
}

/**
 * token验证失败跳转
 * @param next
 * @param to
 */
const noTokenRoute = (next:any, to:any) => {
    if (appState.embedMode) {
        next(routeConst.ERROR_403)
    } else {
        next(`${routeConst.LOGIN}?redirect=${to.fullPath}`)
    }
}

// ---------------------------------------------------------------------------- temp? ------------------------------------------
const catchRoute = { path: '', query: '' }
/**
 * 缓存下路由
 * @param route
 */
export function catchToRoute(path:string, query:any) {
    Object.assign(catchRoute, {
        path,
        query
    })
}
/**
 * 缓存下路由
 * @param route
 */
export function resetDefaultRoute(defaultPath:string) {
    const cpath = catchRoute.path
    if (!cpath || cpath.indexOf(routeConst.ERROR) === 0 || cpath === routeConst.LOGIN) changeRoute(defaultPath)
   else changeRoute(catchRoute.path, catchRoute.query, true)
}

/**
 * 返回重新登录
 */
export function changeToLogin() {
    clearToken()
    changeRoute(routeConst.LOGIN, {}, true)
}
// ---------------------------------------------------------------------------- temp-end ------------------------------------------
/**
 * 路由拦截
 */
router.beforeEach((to:any, _from, next) => {
    NProgress.start()
    showAppLoading(true)
    to.meta.title && setDocumentTitle(to.meta.title)
    // 如果不是嵌入模式默认跳转到登录否则跳转到首页
    if (to.path === '/') {
        next(appState.userInit ? appState.defaultRoute : routeConst.LOGIN)
        return
    }
    // 如果是登录和错误界面直接跳转
    if (to.path.indexOf(routeConst.ERROR) === 0 || to.path === routeConst.LOGIN) {
        next()
        return
    }

    const flag = validToken()
    // token被清理了
    if (!flag) {
        initReloadSystem()
        return
    }
    // 如果有token而且当前页面已经获得用户信息直接跳转
    if (appState.userInit || appState.debugMode) {
        next()
    }
    // 不影响之前逻辑 如果是非嵌入模式 而且用户信息没有初始化 直接登录
    else {
        catchToRoute(to.path, to.query)
        next(routeConst.LOGIN)
    }
})
router.afterEach((to:any) => {
    NProgress.done()
    showAppLoading(false)
})

export { routeConst }

